
import http from './http.js';
import WXBizDataCrypt from "./WXBizDataCrypt.js"
var jweixin = require('jweixin-module')
var isWxConfigError = false
var isWxConfigEnd = false
import VConsole from 'vconsole';
//const vConsole = new VConsole();

function getUserInfo(succ) {
	let profile = uni.getStorageSync("profile")
	console.log(profile)
	if (profile == void 0 || profile.length == 0) {
		//获取用户信息
		uni.getUserProfile({
			desc:"注册",
			success(res) {
				wx.hideLoading()
				uni.setStorageSync("profile",res.userInfo)
				succ(res.userInfo)
			},
			fail(err) {
				wx.hideLoading()
				console.log(err)
			}
		})
	}else{
		succ(profile)
	}
}

function getLoginCode(succ) {
	uni.login({
		success(res) {
			succ(res.code)
		}
	})
}

function isLogin() {
	var token = uni.getStorageSync("token")
	if (token == void 0 || token.length == 0) {return false}
	return true
}

function isUserInfo() {
	let profile = uni.getStorageSync("profile")
	if (profile == void 0 || profile.length == 0) {
		return false
	}
	return true
}

function isBindPhone() {
	let phone = uni.getStorageSync("phone")
	if (phone == void 0 || phone.length == 0) {
		return false
	}
	return true
}

function loginIfNeed(username,password,succ){
	http.post("/store/login", {"account":username, "password":password}, (res)=> {
		console.log(res)
		uni.setStorageSync("token", res.Token)
		uni.setStorageSync("uid", res.Id)
		succ()
	})
}

function decryptData(encryptedData, iv){
	var sessionKey = uni.getStorageSync("skey")
	var appId = "wx09cd63acf1709730"
	var pc = new WXBizDataCrypt(appId, sessionKey)
	var data = pc.decryptData(encryptedData , iv)
	console.log('解密后 data: ', data)
	return data
}

function updateUserInfo() {

}

function formatTime(timestamp) {
	var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1) + '-';
	var D = (date.getDate()< 10 ? '0'+date.getDate():date.getDate())+ ' ';
	var h = (date.getHours() < 10 ? '0'+date.getHours():date.getHours())+ ':';
	var m = (date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes()) + ':';
	var s = date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds();
	return Y+M+D+h+m+s;
}

function formatTime2(timestamp) {
	var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var Y = date.getFullYear();
	var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1);
	var D = (date.getDate()< 10 ? '0'+date.getDate():date.getDate());
	var h = (date.getHours() < 10 ? '0'+date.getHours():date.getHours());
	var m = (date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes());
	var s = date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds();
	return Y+M+D+h+m+s;
}

function gup(name, url) {
  if (!url) url = location.href;
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(url);
  return results == null ? null : results[1];
}

function getUrlParams(url) {
	let query = url.split("?")[1];
	let zparams = query.split("&");
	var params = {}
	for (var i=0;i<zparams.length;i++) {
		var sp = zparams[i].split("=")
		params[sp[0]] = sp[1]
	}
	
	return params
}

function splitBank(str){
	console.log(str)
	return str.replace(/\s/g, '').replace(/(\d{4})(?=\d)/g, "$1 ");
}

function initWxConfigIfNeed(succ) {
	// this.wxconfig({
	// 	"appid":"wx5e261a404af2450c",
	// 	"noncestr":"KEwsfNNgRc5o",
	// 	"sign":"ca5678d7ffc49a0a16e0ab61e679fba68b486e51",
	// 	"timestamp":"1621586048"
	// })
	// return
	// if (isWxConfigEnd) {
	// 	succ()
	// 	return
	// }
	http.get("/store/wxconfig", {"url":getCurLocationUrl()}, (res)=>{
		wxconfig(res, succ)
	})
}

function getCurLocationUrl(){
	if (uni.getSystemInfoSync().platform === 'ios'){
		return uni.getStorageSync("enterurl")?uni.getStorageSync("enterurl"):location.href
	}
	return location.href
}

function wxconfig(res, succ) {
	jweixin.config({
		debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。  
		appId: res.appid, // 必填，公众号的唯一标识  
		timestamp: res.timestamp, // 必填，生成签名的时间戳  
		nonceStr: res.noncestr, // 必填，生成签名的随机串  
		signature: res.sign, // 必填，签名，见附录1  
		surl: getCurLocationUrl(), //自己添加的，debug为true的时候可以网页打印出对应的URL是否正确  
		jsApiList: ["scanQRCode"]
	});
	jweixin.ready(function() {
		if (isWxConfigError == false) {
			isWxConfigEnd = true
			succ()
		}
	})
	jweixin.error(function(err) {
		console.log(err)
		isWxConfigError = true
	})
}

function scanQrCode(succ) {
	jweixin.scanQRCode({
		needResult:1,
		scanType: ["barCode"],
		success(r){
			var ss = r.resultStr.split(",")
			if (ss.length > 0) {
				succ(ss[ss.length-1])
			}
		},
		fail(err) {
			uni.showToast({
				icon:'none',
				title:err.errMsg,
			})
		}
	})
}

function clearNoNum(text){
	text = text.toString()
	var nText = text.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
	nText = nText.replace(/^\./g,"");  //验证第一个字符是数字而不是.
	nText = nText.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的.
	nText = nText.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
	return nText
}

function getKefuPhone(succ) {
	succ("10010")
	return
	http.get("/customerphone", {}, (r)=>{
		console.log(r)
		succ(r)
	}, "正在获取")
}


function showKefu(succ) {
	getKefuPhone((r)=>{
		var ph = r
		uni.showActionSheet({
			title:ph,
			itemList:[
				"呼叫"
			],
			complete(res) {
				if (res.tapIndex == 0) {
					uni.makePhoneCall({
						phoneNumber:ph
					})
				}
			}
		})
	})
}

export default {
	getUserInfo,
	getLoginCode,
	isLogin,
	loginIfNeed,
	isUserInfo,
	isBindPhone,
	decryptData,
	formatTime,
	gup,
	getUrlParams,
	initWxConfigIfNeed,
	scanQrCode,
	formatTime2,
	clearNoNum,
	showKefu,
	splitBank
}